/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict'

angular.module('flowableApp').controller('instanceController', [
  '$rootScope',
  '$scope',
  '$location',
  '$routeParams',
  '$http',
  '$translate',
  'appResourceRoot',
  '$modal',
  function($rootScope, $scope, $location, $routeParams, $http, $translate, appResourceRoot, $modal) {
    var instanceinfo = JSON.parse($routeParams.instanceinfo)
    $rootScope.rev = instanceinfo.rev || ''
    $scope.instanceId = instanceinfo.id
    $scope.suspensionState = instanceinfo.suspensionState
    $rootScope.instanceTask = { activeTab: 'task' }

    $scope.instanceTabs = [
      {
        id: 'task',
        title: $translate.instant('GENERAL.NAVIGATION.TASKS'),
        num: 0
      },
      {
        id: 'param',
        title: $translate.instant('GENERAL.NAVIGATION.PARAM'),
        num: 0
      }
    ]

    //获取流程实例信息
    $scope.loadInstance = function() {
      $http({
        method: 'GET',
        url: FLOWABLE.CONFIG.adminContextRoot + '/app/rest/admin/process-instances/' + $scope.instanceId
      }).success(function(response, status, headers, config) {
        response.status = response.endTime ? $translate.instant('COMMON.DONE') : $translate.instant('COMMON.DOING')
        $rootScope.processInstance = response
      })
    }
    $scope.loadInstance()
    //获取流程对应的任务
    $scope.getTasks = function() {
      $http({
        method: 'GET',
        url: FLOWABLE.CONFIG.adminContextRoot + '/app/rest/admin/process-instances/' + $scope.instanceId + '/tasks'
      }).success(function(res) {
        $scope.instanceTabs[0].num = res.total
        $scope.tasksList = res.data
      })
    }
    $scope.getTasks()
    //获取流程对应的表单变量
    $scope.getFormVariables = function() {
      $http({
        method: 'GET',
        url: FLOWABLE.CONFIG.adminContextRoot + '/app/rest/admin/process-instances/' + $scope.instanceId + '/variables'
      }).success(function(res) {
        $scope.instanceTabs[1].num = res.total
        $scope.formVariables = res.data
      })
    }
    $scope.getFormVariables()
    //跳转到详情页
    $scope.goToDetail = function(task) {
      $location.path('/task/' + task.id)
    }
    //打开加签弹窗
    $scope.openAddDelExecution = function(e, task) {
      e.stopPropagation()
      $scope.approvalResult = 'addExecution'
      $scope.nodeId = task.taskDefinitionKey
      $scope.proInstId = task.processInstanceId
      _internalCreateModal(
        {
          template: appResourceRoot + 'views/popover/approval-template.html',
          scope: $scope
        },
        $modal,
        $scope
      )
    }
    //打开减签弹窗
    $scope.openConfirmPop = function(e, task) {
      e.stopPropagation()
      $scope.excutionId = task.executionId
      $scope.processInstanceId = task.processInstanceId
      $scope.isAdd = true
      _internalCreateModal(
        {
          template: appResourceRoot + 'views/popover/confirm-pop.html',
          scope: $scope
        },
        $modal,
        $scope
      )
    }
  }
])

angular.module('flowableApp').controller('TaskController', [
  '$rootScope',
  '$scope',
  '$translate',
  '$timeout',
  '$location',
  '$modal',
  '$popover',
  'appResourceRoot',
  'CommentService',
  'TaskService',
  '$routeParams',
  'AppDefinitionService',
  function(
    $rootScope,
    $scope,
    $translate,
    $timeout,
    $location,
    $modal,
    $popover,
    appResourceRoot,
    CommentService,
    TaskService,
    $routeParams,
    AppDefinitionService
  ) {
    // Ensure correct main page is set
    $rootScope.setMainPageById('tasks')
    // $rootScope.rev = $routeParams.rev || ''
    $scope.selectedTask = { id: $routeParams.taskId }

    $scope.appDefinitionKey = $routeParams.appDefinitionKey

    $scope.$on('task-completed', function(event, data) {
      $rootScope.addAlertPromise($translate('TASK.ALERT.COMPLETED', data))
      $scope.openTasks()
    })

    $scope.openTasks = function(task) {
      var path = ''
      if ($rootScope.activeAppDefinition && !FLOWABLE.CONFIG.integrationProfile) {
        path = '/apps/' + $rootScope.activeAppDefinition.id
      }
      $location.path(path + '/tasks')
    }
  }
])

angular.module('flowableApp').controller('TaskDetailController', [
  '$rootScope',
  '$scope',
  '$translate',
  '$http',
  '$location',
  '$routeParams',
  'appResourceRoot',
  'CommentService',
  'TaskService',
  'FormService',
  'RelatedContentService',
  '$timeout',
  '$modal',
  '$popover',
  function(
    $rootScope,
    $scope,
    $translate,
    $http,
    $location,
    $routeParams,
    appResourceRoot,
    CommentService,
    TaskService,
    FormService,
    RelatedContentService,
    $timeout,
    $modal,
    $popover
  ) {
    $scope.model = {
      // Indirect binding between selected task in parent scope to have control over display
      // before actual selected task is switched
      task: $scope.selectedTask,
      completeButtonDisabled: false,
      claimButtonDisabled: false,
      uploadInProgress: false
    }

    $scope.activeTab = 'form'

    $scope.model.involvementSummary = {
      loading: false
    }

    $scope.model.contentSummary = {
      loading: false
    }

    $scope.model.commentSummary = {
      loading: false
    }

    $scope.model.subTaskSummary = {
      loading: false
    }

    //回到流程实例弹窗页
    $scope.backToInstance = function() {
      window.history.go(-1)
    }

    $scope.resetModel = function() {
      // Reset tabs
      $scope.taskTabs = []
      if ($scope.model.task.formKey != null) {
        $scope.taskTabs.push({
          id: 'form',
          title: 'TASK.TITLE.FORM'
        })
        $scope.activeTab = 'form'
      } else {
        $scope.activeTab = 'details'
      }

      $scope.taskTabs.push({
        id: 'details',
        title: 'TASK.TITLE.DETAILS'
      })

      // Reset summary model
      $scope.model.involvementSummary = {
        loading: true
      }

      $scope.model.contentSummary = {
        loading: true
      }

      $scope.model.commentSummary = {
        loading: true
      }

      $scope.model.subTaskSummary = {
        loading: true
      }

      $scope.model.content = undefined
      $scope.model.comments = undefined

      $timeout(function() {
        // Force refresh of all auto-height components as the tabs can be hidden or shown
        $rootScope.window.forceRefresh = true
      }, 100)

      var today = new Date()
      $scope.today = new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0, 0)
    }

    $scope.showFlowChart = function() {
      $scope.model.processInstance = $rootScope.processInstance
      _internalCreateModal(
        {
          template: appResourceRoot + 'views/modal/process-instance-graphical.html',
          scope: $scope,
          show: true
        },
        $modal,
        $scope
      )
    }
    //打开撤销确认弹框
    $scope.openConfirmModal = function(result) {
      $scope.approvalResult = result
      _internalCreateModal(
        {
          template: appResourceRoot + 'views/popover/confirm-pop.html',
          scope: $scope
        },
        $modal,
        $scope
      )
    }
    //打开审批历史弹框
    $scope.showApproveHistory = function() {
      $scope.model.processInstance = $rootScope.processInstance
      _internalCreateModal(
        {
          template: appResourceRoot + 'views/popover/history-table.html',
          scope: $scope
        },
        $modal,
        $scope
      )
    }
    //打开审批同意/驳回/转办/终止/挂起/激活弹框
    $scope.openApprovalModal = function(result) {
      $scope.approvalResult = result
      if ($scope.model.task) {
        $scope.noFormTaskId = $scope.model.task.id
      }
      _internalCreateModal(
        {
          template: appResourceRoot + 'views/popover/approval-template.html',
          scope: $scope
        },
        $modal,
        $scope
      )
    }
    //打开预取步骤页
    $scope.goToSteps = function(){
      window.open(`${window.location.origin}/static/prefetchSteps.html?id=${$rootScope.processInstance.id}`)
    }
    //提交流程
    $scope.startProcess = function() {
      var params = {
        actionState: 1,
        taskId: $scope.model.task.id,
        message: '流程提交'
      }
      FormService.agreeTask(params).then(function(data) {
        window.$callParent('CloseModelWindowAndRefresh')
      })
    }

    $scope.showPrint = function() {
      window.print()
    }

    $scope.closeModelWindow = function() {
      if (window.parent.location.href.indexOf('static') != -1) {
        window.location = window.origin + '/#/to-do'
      }
      window.$callParent('CloseModelWindow')
    }

    $scope.showPeople = function() {
      $scope.activeTab = 'details'
    }
    $scope.showContent = function() {
      $scope.activeTab = 'details'
    }
    $scope.showComments = function() {
      $scope.activeTab = 'details'
    }
    $scope.showSubTasks = function() {
      $scope.activeTab = 'details'
    }
    $scope.toggleForm = function() {
      if ($scope.activeTab == 'form') {
        $scope.activeTab = 'details'
      } else {
        $scope.activeTab = 'form'
      }
    }

    // The selected task is set by the parent, eg in tasks.js
    $scope.$watch('selectedTask', function(newValue) {
      if (newValue != $scope.selectedOldValue && newValue && newValue.id) {
        $scope.model.taskUpdating = true
        $scope.model.task = newValue
        $scope.model.claimButtonDisabled = false
        if ($scope.model.task.formKey) {
          $scope.resetModel()
        }
        $scope.getTask(newValue.id)
      } else {
        // Reset whole model to make sure nothing is left behind in case a new task will
        // be selected in the future
        $scope.model = {}
      }
      $scope.selectedOldValue = newValue
    })

    // Ensure correct main page is set
    $rootScope.setMainPageById('tasks')

    $scope.setTaskAssigneeValue = function(user) {
      var alertData = {
        firstName: user.firstName,
        lastName: user.lastName,
        taskName: $scope.model.task.name
      }

      TaskService.assignTask($scope.model.task.id, user.id).then(function(data) {
        $rootScope.addAlertPromise($translate('TASK.ALERT.ASSIGNED', alertData))
        $scope.model.task = data
      })
    }

    $scope.setTaskAssigneeValueByEmail = function(email) {
      TaskService.assignTaskByEmail($scope.model.task.id, email).then(function() {
        $scope.model.task.assignee = { email: email } // Faking a user (since it will only be an email address)
      })
    }

    $scope.involvePerson = function(user) {
      var alertData = {
        firstName: user.firstName,
        lastName: user.lastName,
        taskName: $scope.model.task.name
      }

      TaskService.involveUserInTask(user.id, $scope.model.task.id).then(function() {
        $rootScope.addAlertPromise($translate('TASK.ALERT.PERSON-INVOLVED', alertData))

        if (!$scope.model.task.involvedPeople) {
          $scope.model.task.involvedPeople = [user]
        } else {
          $scope.model.task.involvedPeople.push(user)
        }
      })
    }

    $scope.involvePersonByEmail = function(email) {
      TaskService.involveUserInTaskByEmail(email, $scope.model.task.id).then(function() {
        if (!$scope.model.task.involvedPeople) {
          $scope.model.task.involvedPeople = { email: email }
        } else {
          $scope.model.task.involvedPeople.push({ email: email })
        }
      })
    }

    $scope.removeInvolvedUser = function(user) {
      var alertData = {
        firstName: user.firstName,
        lastName: user.lastName,
        taskName: $scope.model.task.name
      }

      TaskService.removeInvolvedUserInTask(user, $scope.model.task.id).then(function() {
        $rootScope.addAlertPromise($translate('TASK.ALERT.PERSON-NO-LONGER-INVOLVED', alertData))

        $scope.model.task.involvedPeople.splice($.inArray(user, $scope.model.task.involvedPeople), 1)
      })
    }

    $scope.getTask = function(taskId) {
      $scope.model.loading = true
      $scope.model.formData = undefined
      $scope.model.hasFormKey = false
      if ($scope.model.task.formKey) {
        $scope.model.hasFormKey = true
      }

      $http({ method: 'GET', url: FLOWABLE.CONFIG.contextRoot + '/app/rest/tasks/' + taskId })
        .success(function(response, status, headers, config) {
          // Do not replace the model, as it's still used in the task-list
          angular.extend($scope.model.task, response)
          //判断是否显示保存草稿按钮
          var taskId = response.id || 'Null'
          FormService.isCanSave({ taskId: taskId }).then(function(res) {
            $scope.canSave = res
          })

          $scope.model.loading = false
          $scope.noSuchTask = false

          if (!$scope.model.hasFormKey) {
            $scope.resetModel()
          }

          $scope.loadComments()
          $scope.loadRelatedContent()
          $scope.loadSubTasks()

          if ($scope.model.task.processInstanceId) {
            $scope.loadProcessInstance()
          } else {
            $scope.model.processInstance = undefined
          }

          if ($scope.model.task.scopeId) {
            $scope.loadCaseInstance()
          } else {
            $scope.model.caseInstance = undefined
          }

          $scope.refreshInvolvmentSummary()

          // Loading form already
          if ($scope.model.task.formKey !== null && $scope.model.task.formKey !== undefined) {
            FormService.getTaskForm($scope.model.task.id).then(function(formData) {
              $scope.model.formData = formData
            })
          } else {
            $scope.model.formData = undefined
          }

          $scope.model.taskUpdating = false
        })
        .error(function(response, status, headers, config) {
          $scope.noSuchTask = true
        })
    }

    $scope.$watch(
      'model.task.involvedPeople',
      function(newValue) {
        $scope.refreshInvolvmentSummary()
      },
      true
    )

    $scope.refreshInvolvmentSummary = function() {
      if ($scope.model.task) {
        var newValue = $scope.model.task.involvedPeople
        $scope.model.involvementSummary.loading = false
        if (newValue && newValue.length > 0) {
          $scope.model.involvementSummary.count = newValue.length

          if (newValue.length > 8) {
            $scope.model.involvementSummary.overflow = true
            $scope.model.involvementSummary.items = []

            for (var i = 0; i < 8; i++) {
              $scope.model.involvementSummary.items.push(newValue[i])
            }
          } else {
            $scope.model.involvementSummary.overflow = false
            $scope.model.involvementSummary.items = newValue
          }
        } else {
          $scope.model.involvementSummary.count = 0
        }
      }
    }

    $scope.$watch(
      'model.content.data',
      function(newValue) {
        if ($scope.model.task) {
          $scope.model.contentSummary.loading = false
          if (newValue && newValue.length > 0) {
            $scope.model.contentSummary.count = newValue.length

            if (newValue.length > 8) {
              $scope.model.contentSummary.overflow = true
              $scope.model.contentSummary.items = []

              for (var i = 0; i < 8; i++) {
                $scope.model.contentSummary.items.push(newValue[i])
              }
            } else {
              $scope.model.contentSummary.overflow = false
              $scope.model.contentSummary.items = newValue
            }
          } else {
            $scope.model.contentSummary.count = 0
          }
        }
      },
      true
    )

    $scope.$watch(
      'model.comments.data',
      function(newValue) {
        $scope.refreshCommentSummary()
      },
      true
    )

    $scope.$watch(
      'model.subTasks.data',
      function(newValue) {
        $scope.refreshSubTaskSummary()
      },
      true
    )

    $scope.refreshCommentSummary = function() {
      if ($scope.model.task) {
        var newValue = $scope.model.comments ? $scope.model.comments.data : undefined
        $scope.model.commentSummary.loading = false

        if (newValue) {
          $scope.model.commentSummary.count = newValue.length
        } else {
          $scope.model.commentSummary.loading = true
          $scope.model.commentSummary.count = undefined
        }
      }
    }

    $scope.refreshSubTaskSummary = function() {
      if ($scope.model.task) {
        var newValue = $scope.model.subTasks ? $scope.model.subTasks : undefined
        $scope.model.subTaskSummary.loading = false

        if (newValue) {
          $scope.model.subTaskSummary.count = newValue.length
        } else {
          $scope.model.subTaskSummary.loading = true
          $scope.model.subTaskSummary.count = undefined
        }
      }
    }

    $scope.dragOverContent = function(over) {
      if (over && !$scope.model.contentSummary.addContent) {
        $scope.model.contentSummary.addContent = true
      }
    }

    $scope.$watch(
      'model.content.data',
      function(newValue) {
        if ($scope.model.task) {
        }
      },
      true
    )

    $scope.loadComments = function() {
      CommentService.getTaskComments($scope.model.task.id).then(function(data) {
        $scope.model.comments = data

        $scope.refreshCommentSummary()
      })
    }

    $scope.loadSubTasks = function() {
      TaskService.getSubTasks($scope.model.task.id).then(function(data) {
        $scope.model.subTasks = data

        $scope.refreshSubTaskSummary()
      })
    }

    $scope.toggleCreateComment = function() {
      if ($scope.model.commentSummary.addComment) {
        $scope.model.commentSummary.newComment = undefined
      }

      $scope.model.commentSummary.addComment = !$scope.model.commentSummary.addComment

      if ($scope.model.commentSummary.addComment) {
        $timeout(function() {
          angular.element('.focusable').focus()
        }, 100)
      }
    }

    $scope.toggleCreateContent = function() {
      $scope.model.contentSummary.addContent = !$scope.model.contentSummary.addContent
    }

    $scope.onContentUploaded = function(content) {
      if ($scope.model.content && $scope.model.content.data) {
        $scope.model.content.data.push(content)
        RelatedContentService.addUrlToContent(content)
        $scope.model.selectedContent = content
      }
      $rootScope.addAlertPromise($translate('TASK.ALERT.RELATED-CONTENT-ADDED', content), 'info')
      $scope.toggleCreateContent()
    }

    $scope.onContentDeleted = function(content) {
      if ($scope.model.content && $scope.model.content.data) {
        $scope.model.content.data.forEach(function(value, i, arr) {
          if (content === value) {
            arr.splice(i, 1)
          }
        })
      }
    }

    $scope.selectContent = function(content) {
      if ($scope.model.selectedContent == content) {
        $scope.model.selectedContent = undefined
      } else {
        $scope.model.selectedContent = content
      }
    }

    $scope.confirmNewComment = function() {
      $scope.model.commentSummary.loading = true
      CommentService.createTaskComment($scope.model.task.id, $scope.model.commentSummary.newComment.trim()).then(
        function(comment) {
          $scope.model.commentSummary.newComment = undefined
          $scope.model.commentSummary.addComment = false
          $scope.model.commentSummary.loading = false
          $rootScope.addAlertPromise($translate('TASK.ALERT.COMMENT-ADDED', $scope.model.task))
          $scope.loadComments()
        }
      )
    }

    $scope.$watch('model.task.dueDate', function(newValue, oldValue) {
      if (!$scope.model.taskUpdating && $scope.model.task) {
        // Update task due-date

        if (
          (oldValue === null && newValue === null) ||
          (oldValue === null && newValue === undefined) ||
          (oldValue === undefined && newValue === undefined) ||
          (oldValue === undefined && newValue === null)
        ) {
          return
        }

        // Normalize the date to midnight
        if (newValue && newValue !== undefined && newValue.getHours && newValue.getHours() != 23) {
          newValue.setHours(23)
          newValue.setMinutes(59)
          newValue.setSeconds(59)
          $scope.model.task.dueDate = newValue
        }

        if (new Date(oldValue).getTime() != new Date(newValue).getTime() || (oldValue != null && newValue != null)) {
          $scope.model.taskUpdating = true
          // Explicitly force NULL value when undefined to make sure the null
          // is sent to the service
          var data = {
            dueDate: newValue ? newValue : null
          }
          TaskService.updateTask($scope.model.task.id, data).then(function(response) {
            $scope.model.taskUpdating = false
          })
        }
      }
    })

    $scope.createTaskInline = function() {
      if (!$scope.newTask) {
        $scope.newTask = {
          name: 'New task',
          inline: true
        }
      }
    }

    $scope.createProcess = function() {
      $rootScope.createProcessInstance = true
      $scope.openProcessInstance()
    }

    $scope.selectProcessDefinition = function(definition) {
      $scope.newProcessInstance.processDefinitionId = definition.id
      $scope.newProcessInstance.name = definition.name + ' - ' + new moment().format('MMMM Do YYYY')

      $timeout(function() {
        angular.element('#start-process-name').focus()
      }, 20)
    }

    $scope.closeInlineTaskCreation = function($event) {
      $scope.newTask = undefined
      $event.stopPropagation()
    }

    $scope.setTaskAssignee = function(user) {
      $scope.newTask.assignee = user
    }

    $scope.createSubTask = function(element) {
      // Create popover
      if (!$scope.createTaskPopover) {
        $scope.newTask = {
          name: 'New task'
        }

        $scope.createTaskPopover = $popover(angular.element(element), {
          template: appResourceRoot + 'views/popover/create-task-popover.html',
          placement: 'bottom-right',
          show: true,
          scope: $scope
        })

        $scope.createTaskPopover.$scope.$on('tooltip.hide', function() {
          $scope.createTaskPopover.$scope.$destroy()
          $scope.createTaskPopover.destroy()
          $scope.createTaskPopover = undefined

          $scope.newTask = undefined
        })
      }
    }

    $scope.confirmTaskCreation = function(newTask) {
      if (!newTask) {
        newTask = $scope.newTask
      }
      if (newTask && newTask.name) {
        var taskData = {
          name: newTask.name,
          description: newTask.description,
          assignee: newTask.assignee ? newTask.assignee.id : null
        }

        taskData.parentTaskId = '' + $scope.model.task.id

        if ($rootScope.activeAppDefinition) {
          taskData.category = '' + $rootScope.activeAppDefinition.id
        }

        newTask.loading = true
        TaskService.createTask(taskData).then(function(task) {
          newTask.loading = false

          if ($scope.createTaskPopover) {
            $scope.createTaskPopover.$scope.$destroy()
            $scope.createTaskPopover.destroy()
            $scope.createTaskPopover = undefined
          }

          $rootScope.addAlertPromise($translate('TASK.ALERT.CREATED', task))
        })
      }
    }

    $scope.completeTask = function() {
      $scope.model.completeButtonDisabled = true
      TaskService.completeTask($scope.model.task.id)
    }

    $scope.claimTask = function() {
      $scope.model.loading = true
      $scope.model.claimButtonDisabled = true
      TaskService.claimTask($scope.model.task.id).then(function(data) {
        // Refetch data on claim success
        $scope.getTask($scope.model.task.id)
      })
    }

    $scope.loadProcessInstance = function() {
      $http({
        method: 'GET',
        url: FLOWABLE.CONFIG.contextRoot + '/app/rest/process-instances/' + $scope.model.task.processInstanceId
      })
        .success(function(response, status, headers, config) {
          $scope.model.processInstance = response
          $rootScope.processInstance = response
          if (response && !$scope.approvalResult) {
            FormService.isCancel({ procInstId: response.id }).then(function(res) {
              $rootScope.isCancel = res
              $scope.isCancel = res
            })
          }
        })
        .error(function(response, status, headers, config) {
          // Do nothing. User is not allowed to see the process instance
        })
    }

    //催办
    $scope.urge = function() {
      $http({
        method: 'POST',
        url: FLOWABLE.CONFIG.contextRoot + '/app/rest/urge/toUrge/' + $scope.model.task.processInstanceId
      }).success(function(response, status, headers, config) {
        if (status == 200) {
          $rootScope.alerts['current'] = {
            type: 'alert-success',
            message: $translate.instant('TASK.ALERT.URGE-SUCCESS')
          }
          $timeout(function() {
            $rootScope.alerts['current'] = ''
          }, 3000)
        }
      })
    }

    $scope.openProcessInstance = function(id) {
      $rootScope.root.selectedProcessId = id
      var path = ''
      if ($rootScope.activeAppDefinition && !FLOWABLE.CONFIG.integrationProfile) {
        path = '/apps/' + $rootScope.activeAppDefinition.id
      }
      $location.path(path + '/processes')
    }

    $scope.loadCaseInstance = function() {
      $http({
        method: 'GET',
        url: FLOWABLE.CONFIG.contextRoot + '/app/rest/case-instances/' + $scope.model.task.scopeId
      })
        .success(function(response, status, headers, config) {
          $scope.model.caseInstance = response
        })
        .error(function(response, status, headers, config) {
          // Do nothing. User is not allowed to see the process instance
        })
    }

    $scope.openCaseInstance = function(id) {
      $rootScope.root.selectedCaseId = id
      var path = ''
      if ($rootScope.activeAppDefinition && !FLOWABLE.CONFIG.integrationProfile) {
        path = '/apps/' + $rootScope.activeAppDefinition.id
      }
      $location.path(path + '/cases')
    }

    $scope.openTaskInstance = function(taskId) {
      $rootScope.root.selectedTaskId = taskId
      $scope.refreshFilter()
    }

    $scope.returnToTaskList = function() {
      var path = ''
      if ($rootScope.activeAppDefinition && !FLOWABLE.CONFIG.integrationProfile) {
        path = '/apps/' + $rootScope.activeAppDefinition.id
      }
      $location.path(path + '/tasks')
    }

    // OLD STUFF

    $scope.returnToList = function() {
      $location.path('/tasks')
    }

    $scope.loadRelatedContent = function() {
      $scope.model.content = undefined
      TaskService.getRelatedContent($scope.model.task.id).then(function(data) {
        $scope.model.content = data
      })
    }

    $scope.$watch(
      'model.content',
      function(newValue) {
        if (newValue && newValue.data && newValue.data.length > 0) {
          var needsRefresh = false
          for (var i = 0; i < newValue.data.length; i++) {
            var entry = newValue.data[i]
            if (!entry.contentAvailable) {
              needsRefresh = true
              break
            }
          }
        }
      },
      true
    )

    $scope.editComment = function() {
      $scope.model.editingComment = true
    }

    $scope.stopEditComment = function() {
      $scope.model.editingComment = false
    }

    $scope.userInvolved = function(user) {
      var alertData = {
        firstName: user.firstName,
        lastName: user.lastName,
        taskName: $scope.model.task.name
      }

      TaskService.involveUserInTask(user.id, $scope.model.task.id).then(function() {
        $rootScope.addAlertPromise($translate('TASK.ALERT.PERSON-INVOLVED', alertData))

        if (!$scope.model.task.involvedPeople) {
          $scope.model.task.involvedPeople = [user]
        } else {
          $scope.model.task.involvedPeople.push(user)
        }
      })
    }

    $scope.assigneeSelected = function(user) {
      var alertData = {
        firstName: user.firstName,
        lastName: user.lastName,
        taskName: $scope.model.task.name
      }

      TaskService.assignTask($scope.model.task.id, user.id).then(function() {
        $rootScope.addAlertPromise($translate('TASK.ALERT.ASSIGNED', alertData))

        $scope.model.task.assignee = user
      })
    }

    $scope.revealContent = function(content) {
      $scope.model.activeTab = 'content'
      $scope.model.selectedContent = content
    }

    $scope.hasDetails = function() {
      if (
        $scope.model.loading == true ||
        $scope.model.involvementSummary === null ||
        $scope.model.involvementSummary === undefined ||
        $scope.model.involvementSummary.loading === true ||
        $scope.model.contentSummary === null ||
        $scope.model.contentSummary === undefined ||
        $scope.model.contentSummary.loading === true ||
        $scope.model.commentSummary === null ||
        $scope.model.commentSummary === undefined ||
        $scope.model.commentSummary.loading === true ||
        $scope.model.subTaskSummary === null ||
        $scope.model.subTaskSummary === undefined ||
        $scope.model.subTaskSummary.loading === true
      ) {
        return false
      }

      if ($scope.model.task !== null && $scope.model.task !== undefined) {
        // Returning true by default, or the screen will flicker until all the data (people/comments/content) have been fetched
        var hasPeople = false
        var hasContent = false
        var hasComments = false
        var hasSubTasks = false

        // Involved people
        if (
          $scope.model.task.involvedPeople !== null &&
          $scope.model.task.involvedPeople !== undefined &&
          $scope.model.task.involvedPeople.length > 0
        ) {
          hasPeople = true
        }

        // Content
        if (
          $scope.model.content !== null &&
          $scope.model.content !== undefined &&
          $scope.model.content.data.length > 0
        ) {
          hasContent = true
        }

        // Comments
        if (
          $scope.model.comments !== null &&
          $scope.model.comments !== undefined &&
          $scope.model.comments.data.length > 0
        ) {
          hasComments = true
        }

        // SubTasks
        if ($scope.model.subTasks !== null && $scope.model.subTasks !== undefined && $scope.model.subTasks.length > 0) {
          hasSubTasks = true
        }

        return hasPeople || hasContent || hasComments || hasSubTasks
      }
      return false
    }

    $scope.uploadInProgress = function(state) {
      if (state !== 'undefined') {
        $scope.model.uploadInProgress = state
      }
    }
  }
])

angular.module('flowableApp').controller('CreateTaskController', [
  '$rootScope',
  '$scope',
  '$translate',
  '$http',
  '$location',
  'TaskService',
  function($rootScope, $scope, $translate, $http, $location, TaskService) {
    $scope.createTask = function() {
      TaskService.createTask($scope.newTask).then(function(createdTask) {
        $scope.resetModel()
        $rootScope.addAlertPromise($translate('TASK.ALERT.CREATED', createdTask))
      })
    }

    $scope.resetModel = function() {
      $scope.newTask = {
        name: '',
        description: ''
      }
    }

    $scope.resetModel()
  }
])

angular.module('flowableApp').controller('ContentDetailsController', [
  '$rootScope',
  '$scope',
  '$translate',
  '$modal',
  'appResourceRoot',
  'RelatedContentService',
  function($rootScope, $scope, $translate, $modal, appResourceRoot, RelatedContentService) {
    $scope.model = {
      selectedContent: $scope.content,
      selectedTask: $scope.task
    }

    // Map simple-type to readable content type name
    var translateKey
    if ($scope.content) {
      translateKey = 'CONTENT.SIMPLE-TYPE.' + $scope.content.simpleType.toUpperCase()
    } else {
      translateKey = 'CONTENT.SIMPLE-TYPE.CONTENT'
    }

    $translate(translateKey).then(function(message) {
      $scope.model.contentType = message
    })

    $scope.getPdfViewerUrl = function(content) {
      var urlEncoded = encodeURIComponent(content.pdfUrl)

      return appResourceRoot + 'views/templates/viewer.html?file=' + urlEncoded
    }

    $scope.deleteContent = function(content, task) {
      var modalInstance = _internalCreateModal(
        {
          template: appResourceRoot + 'views/modal/delete-content.html',
          show: true
        },
        $modal,
        $scope
      )

      modalInstance.$scope.popup = {
        content: content,
        loading: false
      }

      modalInstance.$scope.ok = function() {
        RelatedContentService.deleteContent(content.id, task && task.id).then(function() {
          $scope.$emit('content-deleted', { content: content })
          $scope.model.selectedContent = null
          $scope.model.selectedTask = null
        })
      }
    }
  }
])
